﻿namespace ECommerce.Controls
{
	using System;
	using System.Linq;
	using Data.Entity;
	using System.Collections.Generic;
	using System.Web.UI.WebControls;

	public partial class ProductsByTag : BaseUserControl
	{
		private Service.IProductService _ProductService;
		private Service.IShoppingCartItemService _ShoppingCartItemService;
		private IEnumerable<Product> _DataSource;
		private int _TotalRecords;

		public int TagID
		{
			get
			{
				return CommonHelper.QueryStringInt("tagid");
			}
		}

		public IEnumerable<Product> DataSource
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				if (_ProductService == null)
				{
					_ProductService = new Service.ProductService();
				}

				if (TagID > 0)
				{
					_DataSource = _ProductService.GetProductsByTag(TagID, pageIndex, pageSize, out totalRecords);
					this.TotalRecords = totalRecords;

					return _DataSource;
				}
				else
				{
					var lan = SiteContext.Current.WorkingLanguage;

					if (lan == null)
					{
						totalRecords = 0;
						return null;
					}

					_DataSource = _ProductService.GetProductsByLanguage(lan.LanguageId, pageIndex, pageSize, out totalRecords);
					this.TotalRecords = totalRecords;

					return _DataSource;
				}
			}
		}

		public int PageIndex
		{
			get
			{
				if (ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = DataSource;

				if (data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if (totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if (totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if (totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return this.GridProducts.PageSize;
			}
			set
			{
				this.GridProducts.PageSize = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			this.LinkButtonFirstPage.Text = GetLocalResourceString("ProductList.LinkButtonFirstPageText");
			this.LinkButtonLastPage.Text = GetLocalResourceString("ProductList.LinkButtonLastPageText");
			this.LinkButtonNextPage.Text = GetLocalResourceString("ProductList.LinkButtonNextPageText");
			this.LinkButtonPrePage.Text = GetLocalResourceString("ProductList.LinkButtonPrePageText");
			this.LinkButtonFirstPage1.Text = GetLocalResourceString("ProductList.LinkButtonFirstPageText");
			this.LinkButtonLastPage1.Text = GetLocalResourceString("ProductList.LinkButtonLastPageText");
			this.LinkButtonNextPage1.Text = GetLocalResourceString("ProductList.LinkButtonNextPageText");
			this.LinkButtonPrePage1.Text = GetLocalResourceString("ProductList.LinkButtonPrePageText");
			this.LSortBySelectorLabel.Text = GetLocalResourceString("ProductList.SortBySelectorLabel");
			this.LTotalRecordsLabel.Text = GetLocalResourceString("ProductList.TotalRecordsLabel");
			this.LTotalPagesLabel.Text = GetLocalResourceString("ProductList.TotalPagesLabel");
			this.LTotalRecordsLabel1.Text = GetLocalResourceString("ProductList.TotalRecordsLabel");
			this.LTotalPagesLabel1.Text = GetLocalResourceString("ProductList.TotalPagesLabel");

			BindSortItems();

			BindProducts();

			var currentPageIndex = this.PageIndex;
			var totalPages = TotalPages;

			if (currentPageIndex == 0 || PageSize <= 1)
			{
				LinkButtonPrePage.Enabled = false;
				LinkButtonFirstPage.Enabled = false;
				LinkButtonPrePage1.Enabled = false;
				LinkButtonFirstPage1.Enabled = false;
			}
			else
			{
				LinkButtonPrePage.Enabled = true;
				LinkButtonFirstPage.Enabled = true;
				LinkButtonPrePage1.Enabled = true;
				LinkButtonFirstPage1.Enabled = true;
			}

			if (currentPageIndex == totalPages - 1 || totalPages <= 1)
			{
				LinkButtonLastPage.Enabled = false;
				LinkButtonNextPage.Enabled = false;
				LinkButtonLastPage1.Enabled = false;
				LinkButtonNextPage1.Enabled = false;
			}
			else
			{
				LinkButtonLastPage.Enabled = true;
				LinkButtonNextPage.Enabled = true;
				LinkButtonLastPage1.Enabled = true;
				LinkButtonNextPage1.Enabled = true;
			}

			// set pager index links
			List<PagerIndex> indexs = new List<PagerIndex>();

			if (totalPages <= 10)
			{
				for (int i = 1; i <= totalPages; i++)
				{
					indexs.Add(new PagerIndex(i.ToString()));
				}
			}
			else if (totalPages > 10)
			{
				if (((currentPageIndex / 10) * 10 + 10) > totalPages)
				{
					for (int i = (currentPageIndex / 10) * 10 + 1; i <= totalPages; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
				else if (((currentPageIndex / 10) * 10 + 10) <= totalPages)
				{
					for (int i = (currentPageIndex / 10) * 10 + 1; i <= (currentPageIndex / 10) * 10 + 10; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
			}

			this.RepeaterPageIndex.DataSource = indexs;
			this.RepeaterPageIndex.DataBind();
			this.RepeaterPageIndex1.DataSource = indexs;
			this.RepeaterPageIndex1.DataBind();

			this.LabelTotalPages.Text = totalPages.ToString();
			this.LabelTotalRecords.Text = TotalRecords.ToString();
			this.LabelTotalPages1.Text = totalPages.ToString();
			this.LabelTotalRecords1.Text = TotalRecords.ToString();

			// disenabel the current pagerindex link
			if (RepeaterPageIndex.TemplateControl.Controls.Count > 1)
			{
				for (int i = 0; i < RepeaterPageIndex.Items.Count; i++)
				{
					LinkButton thePagerIndexLink = RepeaterPageIndex.Items[i].FindControl("LinkButtonPageIndex") as LinkButton;

					if (thePagerIndexLink.Text.Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink.Enabled = false;
					}
				}

				for (int i = 0; i < RepeaterPageIndex1.Items.Count; i++)
				{
					LinkButton thePagerIndexLink1 = RepeaterPageIndex1.Items[i].FindControl("LinkButtonPageIndex1") as LinkButton;

					if (thePagerIndexLink1.Text.Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink1.Enabled = false;
					}
				}
			}
		}

		private void BindSortItems()
		{
			if (this.DropDownList_SortBy.Items.Count <= 0)
			{
				this.DropDownList_SortBy.Items.Add(new ListItem(GetLocalResourceString("ProductList.SortByCreateTime")));
				this.DropDownList_SortBy.Items.Add(new ListItem(GetLocalResourceString("ProductList.SortByPriceAsc")));
				this.DropDownList_SortBy.Items.Add(new ListItem(GetLocalResourceString("ProductList.SortByPriceDesc")));
			}
		}

		protected void GridProducts_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if (e.CommandName.Equals("AddToCart"))
			{
				var user = SiteContext.Current.User;

				if (user == null)
				{
					Server.Transfer("~/Login.aspx");
				}

				if (_ShoppingCartItemService == null)
				{
					_ShoppingCartItemService = new Service.ShoppingCartItemService();
				}

				ShoppingCartItem theNewCart = new ShoppingCartItem();

				theNewCart.CreatedOn = DateTime.Now;
				theNewCart.ProductID = int.Parse(e.CommandArgument.ToString());
				theNewCart.Quantity = 1;
				theNewCart.ShoppingCartTypeID = (int)ShoppingCartType_Const.ShoppingCart;
				theNewCart.UpdatedOn = DateTime.Now;
				theNewCart.UserID = new Guid(user.ProviderUserKey.ToString());
				//theNewCart.AttributesXML = System.Xml.Linq.XElement.EmptySequence.FirstOrDefault();

				_ShoppingCartItemService.CreateNewShoppingCartItem(theNewCart);
			}
		}

		private void BindProducts()
		{
			string selectedItem = this.DropDownList_SortBy.SelectedItem.Text.Trim();

			if (selectedItem == GetLocalResourceString("ProductList.SortByCreateTime"))
			{
				var data = DataSource;

				if (data != null)
				{
					data = data.OrderByDescending(exp => exp.CreatedOn);
				}

				GridProducts.DataSource = data;
				GridProducts.DataBind();
			}

			if (selectedItem == GetLocalResourceString("ProductList.SortByPriceAsc"))
			{
				var data = DataSource;

				if (data != null)
				{
					data = data.OrderBy(exp => exp.ListPrice);
				}

				GridProducts.DataSource = data;
				GridProducts.DataBind();
			}

			if (selectedItem == GetLocalResourceString("ProductList.SortByPriceDesc"))
			{
				var data = DataSource;

				if (data != null)
				{
					data = data.OrderByDescending(exp => exp.ListPrice);
				}

				GridProducts.DataSource = data;
				GridProducts.DataBind();
			}
		}

		/// <summary>
		/// paging event handler
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void LinkButtonPaging_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "FirstPage":
					{
						PageIndex = 0;

						//BindProducts();
					}
					break;
				case "PrePage":
					{
						if (PageIndex > 0)
						{
							PageIndex -= 1;
						}

						//BindProducts();
					}
					break;
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						//BindProducts();
					}
					break;
				case "NextPage":
					{
						if (PageIndex < TotalPages)
						{
							PageIndex += 1;
						}

						//BindProducts();
					}
					break;
				case "LastPage":
					{
						PageIndex = TotalPages - 1;

						//BindProducts();
					}
					break;
			}
		}

		protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
		{
			//BindProducts();
		}
	}
}